import { useState, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { trainingApi, legalThinkingApi, debateApi } from '../services/api'
import type { 
  Question, 
  AnswerSubmission, 
  TrainingSession,
  QuestionStructure,
  TechniqueAnalysis,
  ThinkingAnalysis,
  ReasoningGuidance,
  DebateSession
} from '../types'
import DebatePanel from './DebatePanel'
import './TrainingPanel.css'

interface TrainingPanelProps {
  userId: string
  onNavigate?: (tab: string) => void
}

const TrainingPanel = ({ userId, onNavigate }: TrainingPanelProps) => {
  const [session, setSession] = useState<TrainingSession | null>(null)
  const [currentQuestion, setCurrentQuestion] = useState<Question | null>(null)
  const [selectedAnswer, setSelectedAnswer] = useState<string>('')
  const [selectedAnswers, setSelectedAnswers] = useState<string[]>([]) // 多选题选中的答案数组
  const [answerResult, setAnswerResult] = useState<AnswerSubmission | null>(null)
  const [isLoading, setIsLoading] = useState(false)
  const [timeSpent, setTimeSpent] = useState(0)
  const [timer, setTimer] = useState<ReturnType<typeof setInterval> | null>(null)
  
  // Legal-BERT 相关状态
  const [questionStructure, setQuestionStructure] = useState<QuestionStructure | null>(null)
  const [techniqueAnalysis, setTechniqueAnalysis] = useState<TechniqueAnalysis | null>(null)
  const [reasoningGuidance, setReasoningGuidance] = useState<ReasoningGuidance | null>(null)
  const [thinkingAnalysis, setThinkingAnalysis] = useState<ThinkingAnalysis | null>(null)
  const [userNotes, setUserNotes] = useState<string>('')
  const [showThinkingGuide, setShowThinkingGuide] = useState(false)
  const [showTechniqueTips, setShowTechniqueTips] = useState(false)
  const [showDebate, setShowDebate] = useState(false)
  const [debateSession, setDebateSession] = useState<DebateSession | null>(null)

  // 开始训练会话
  const startSession = async () => {
    setIsLoading(true)
    try {
      // 设置超时，避免无限等待
      const timeoutPromise = new Promise((_, reject) => 
        setTimeout(() => reject(new Error('启动超时，请刷新页面重试')), 15000) // 15秒超时
      )
      
      const sessionPromise = trainingApi.startSession(userId)
      const newSession = await Promise.race([sessionPromise, timeoutPromise]) as any
      
      setSession(newSession)
      await loadNextQuestion(newSession.session_id)
    } catch (error) {
      console.error('Failed to start session:', error)
      alert('启动训练失败，请检查网络连接或刷新页面重试')
    } finally {
      setIsLoading(false)
    }
  }

  // 加载下一个题目
  const loadNextQuestion = async (sessionId: string) => {
    setIsLoading(true)
    try {
      const question = await trainingApi.getNextQuestion(sessionId)
      
      // 检查是否所有题目都完成了
      if (question.question_id === 'no_more_questions' || question.is_completed) {
        setCurrentQuestion({
          ...question,
          is_completed: true
        })
        setSelectedAnswer('')
        setAnswerResult(null)
        // 停止计时器
        if (timer) {
          clearInterval(timer)
          setTimer(null)
        }
      } else {
        setCurrentQuestion(question)
        setSelectedAnswer('')
        setSelectedAnswers([]) // 重置多选题答案
        setAnswerResult(null)
        setTimeSpent(0)
        setUserNotes('')
        setThinkingAnalysis(null)
        
        // 启动计时器
        if (timer) {
          clearInterval(timer)
        }
        const newTimer = setInterval(() => {
          setTimeSpent((prev) => prev + 1)
        }, 1000)
        setTimer(newTimer)
        
        // 加载题目时自动分析题目结构和技巧
        if (question.content && question.options) {
          loadQuestionAnalysis(question.content, question.options)
        }
      }
    } catch (error) {
      console.error('Failed to load question:', error)
    } finally {
      setIsLoading(false)
    }
  }

  // 加载题目分析（题目结构、技巧分析、推理引导）
  const loadQuestionAnalysis = async (content: string, options: string[]) => {
    try {
      // 并行加载题目结构分析和技巧分析，设置超时避免阻塞
      const timeoutPromise = new Promise((_, reject) => 
        setTimeout(() => reject(new Error('分析超时')), 10000) // 10秒超时
      )
      
      const analysisPromise = Promise.all([
        legalThinkingApi.analyzeQuestion(content, options).catch(err => {
          console.warn('题目结构分析失败:', err)
          return null
        }),
        legalThinkingApi.analyzeTechnique(content, options).catch(err => {
          console.warn('技巧分析失败:', err)
          return null
        }),
        legalThinkingApi.guideReasoning(content).catch(err => {
          console.warn('推理引导失败:', err)
          return null
        })
      ])
      
      const [structure, technique, guidance] = await Promise.race([
        analysisPromise,
        timeoutPromise
      ]) as any
      
      if (structure) setQuestionStructure(structure)
      if (technique) setTechniqueAnalysis(technique)
      if (guidance) setReasoningGuidance(guidance)
    } catch (error) {
      console.error('加载题目分析失败:', error)
      // 分析失败不影响主流程，继续显示题目
    }
  }

  // 处理选项点击（支持单选和多选）
  const handleOptionClick = (option: string) => {
    const isMultipleChoice = currentQuestion?.type === 'multiple_choice' || currentQuestion?.type === 'indefinite_choice'
    
    if (isMultipleChoice) {
      // 多选题：切换选中状态
      setSelectedAnswers(prev => {
        if (prev.includes(option)) {
          // 如果已选中，则取消选中
          return prev.filter(item => item !== option)
        } else {
          // 如果未选中，则添加到选中列表
          return [...prev, option]
        }
      })
    } else {
      // 单选题：直接设置选中答案
      setSelectedAnswer(option)
    }
  }

  // 提交答案
  const submitAnswer = async () => {
    if (!session || !currentQuestion) return

    const isMultipleChoice = currentQuestion.type === 'multiple_choice' || currentQuestion.type === 'indefinite_choice'
    const finalAnswer = isMultipleChoice 
      ? (selectedAnswers.length > 0 ? selectedAnswers.join('、') : '') // 多选题用"、"连接
      : selectedAnswer

    if (!finalAnswer) return

    // 停止计时器
    if (timer) {
      clearInterval(timer)
      setTimer(null)
    }

    setIsLoading(true)
    try {
      const result = await trainingApi.submitAnswer(
        session.session_id,
        currentQuestion.question_id,
        { answer: finalAnswer }
      )
      setAnswerResult(result)
      
      // 提交答案后，分析思维过程
      if (currentQuestion.content && result.correct_answer) {
        analyzeThinkingProcess(
          currentQuestion.question_id,
          finalAnswer,
          userNotes,
          result.correct_answer,
          currentQuestion.content,
          result.explanation
        )
      }
    } catch (error) {
      console.error('Failed to submit answer:', error)
    } finally {
      setIsLoading(false)
    }
  }

  // 分析思维过程
  const analyzeThinkingProcess = async (
    questionId: string,
    userAnswer: string,
    notes: string,
    correctAnswer: string,
    questionContent: string,
    explanation: string
  ) => {
    try {
      const analysis = await legalThinkingApi.analyzeThinking(
        userId,
        questionId,
        userAnswer,
        notes || '（用户未提供分析过程）',
        correctAnswer,
        questionContent,
        explanation
      )
      setThinkingAnalysis(analysis)
    } catch (error) {
      console.error('分析思维过程失败:', error)
    }
  }

  // 继续下一题
  const continueNext = () => {
    if (session) {
      loadNextQuestion(session.session_id)
    }
  }

  // 清理计时器
  useEffect(() => {
    return () => {
      if (timer) {
        clearInterval(timer)
      }
    }
  }, [timer])

  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins}:${secs.toString().padStart(2, '0')}`
  }

  return (
    <div className="training-panel">
      {!session ? (
        <motion.div
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          className="session-start"
        >
          <h2>开始训练</h2>
          <p>准备好开始你的法律思维训练了吗？</p>
          <button
            className="start-button"
            onClick={startSession}
            disabled={isLoading}
          >
            {isLoading ? '启动中...' : '开始训练'}
          </button>
        </motion.div>
      ) : (
        <div className="training-content">
          {/* 完成所有题目提示 */}
          {currentQuestion && currentQuestion.is_completed && (
            <motion.div
              initial={{ opacity: 0, scale: 0.9 }}
              animate={{ opacity: 1, scale: 1 }}
              className="completion-card"
            >
              <div className="completion-icon">🎉</div>
              <h2>{currentQuestion.content || '恭喜！您已经完成了当前题库中的所有题目。'}</h2>
              <p className="completion-message">
                太棒了！您已经完成了当前训练会话中的所有题目。
                <br />
                继续学习可以巩固知识，或者尝试其他训练模式。
              </p>
              
              <div className="completion-actions">
                <button
                  className="action-button primary"
                  onClick={async () => {
                    // 重新开始训练（清空已做题目记录）
                    if (session) {
                      setIsLoading(true)
                      try {
                        // 调用重置会话API
                        await trainingApi.resetSession(session.session_id)
                        // 重新加载题目
                        await loadNextQuestion(session.session_id)
                      } catch (error) {
                        console.error('重置会话失败:', error)
                        // 即使重置失败，也尝试重新加载
                        await loadNextQuestion(session.session_id)
                      } finally {
                        setIsLoading(false)
                      }
                    }
                  }}
                  disabled={isLoading}
                >
                  {isLoading ? '重置中...' : '🔄 重新开始训练'}
                </button>
                <button
                  className="action-button"
                  onClick={() => {
                    // 切换到每日学习
                    if (onNavigate) {
                      onNavigate('daily-learning')
                    }
                  }}
                >
                  📚 去每日学习
                </button>
                <button
                  className="action-button"
                  onClick={() => {
                    // 查看进度
                    if (onNavigate) {
                      onNavigate('progress')
                    }
                  }}
                >
                  📊 查看进度
                </button>
                <button
                  className="action-button"
                  onClick={() => {
                    // 开始新的训练会话
                    setSession(null)
                    setCurrentQuestion(null)
                    setAnswerResult(null)
                  }}
                >
                  ➕ 开始新会话
                </button>
              </div>
            </motion.div>
          )}

          {/* 题目区域 */}
          {currentQuestion && !currentQuestion.is_completed && !answerResult && (
            <motion.div
              key={currentQuestion.question_id}
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              className="question-card"
            >
              <div className="question-header">
                <span className="question-type">{currentQuestion.type}</span>
                <span className="question-difficulty">{currentQuestion.difficulty}</span>
                <span className="timer">{formatTime(timeSpent)}</span>
              </div>
              
              <div className="question-content">
                <h3>{currentQuestion.content}</h3>
              </div>

              {/* 思维引导和技巧提示按钮 */}
              {(reasoningGuidance || techniqueAnalysis) && (
                <div className="thinking-tools">
                  <button
                    className="tool-button"
                    onClick={() => setShowThinkingGuide(!showThinkingGuide)}
                  >
                    {showThinkingGuide ? '隐藏' : '显示'} 思维引导
                  </button>
                  <button
                    className="tool-button"
                    onClick={() => setShowTechniqueTips(!showTechniqueTips)}
                  >
                    {showTechniqueTips ? '隐藏' : '显示'} 技巧提示
                  </button>
                </div>
              )}

              {/* 思维引导面板 */}
              {showThinkingGuide && reasoningGuidance && (
                <motion.div
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: 'auto' }}
                  className="thinking-guide-panel"
                >
                  <h4>🧠 思维引导</h4>
                  {reasoningGuidance.guidance.next_steps.length > 0 && (
                    <div className="guidance-steps">
                      <strong>下一步建议：</strong>
                      <ul>
                        {reasoningGuidance.guidance.next_steps.map((step, idx) => (
                          <li key={idx}>{step}</li>
                        ))}
                      </ul>
                    </div>
                  )}
                  {reasoningGuidance.guidance.warnings.length > 0 && (
                    <div className="guidance-warnings">
                      <strong>⚠️ 注意事项：</strong>
                      <ul>
                        {reasoningGuidance.guidance.warnings.map((warning, idx) => (
                          <li key={idx}>{warning}</li>
                        ))}
                      </ul>
                    </div>
                  )}
                  {reasoningGuidance.key_facts.length > 0 && (
                    <div className="key-facts">
                      <strong>关键事实：</strong>
                      <ul>
                        {reasoningGuidance.key_facts.slice(0, 3).map((fact, idx) => (
                          <li key={idx}>
                            <span className="fact-type">{fact.type}</span>: {fact.text.substring(0, 50)}...
                          </li>
                        ))}
                      </ul>
                    </div>
                  )}
                </motion.div>
              )}

              {/* 技巧提示面板 */}
              {showTechniqueTips && techniqueAnalysis && (
                <motion.div
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: 'auto' }}
                  className="technique-tips-panel"
                >
                  <h4>💡 答题技巧</h4>
                  <div className="strategy-section">
                    <strong>整体策略：</strong>
                    <p>{techniqueAnalysis.strategy.overall_strategy}</p>
                  </div>
                  {techniqueAnalysis.strategy.step_by_step.length > 0 && (
                    <div className="steps-section">
                      <strong>分步策略：</strong>
                      <ol>
                        {techniqueAnalysis.strategy.step_by_step.map((step, idx) => (
                          <li key={idx}>{step}</li>
                        ))}
                      </ol>
                    </div>
                  )}
                  {techniqueAnalysis.traps.prevention_tips.length > 0 && (
                    <div className="traps-section">
                      <strong>陷阱提示：</strong>
                      <ul>
                        {techniqueAnalysis.traps.prevention_tips.map((tip, idx) => (
                          <li key={idx}>{tip}</li>
                        ))}
                      </ul>
                    </div>
                  )}
                </motion.div>
              )}

              {/* 用户笔记输入 */}
              <div className="notes-section">
                <label>
                  <strong>📝 我的思考过程（可选）：</strong>
                  <textarea
                    className="notes-input"
                    value={userNotes}
                    onChange={(e) => setUserNotes(e.target.value)}
                    placeholder="记录你的分析思路、推理过程..."
                    rows={3}
                  />
                </label>
              </div>

              {currentQuestion.options && currentQuestion.options.length > 0 && (
                <div className="options-list">
                  <div className="question-type-hint">
                    {currentQuestion.type === 'multiple_choice' || currentQuestion.type === 'indefinite_choice' 
                      ? '📌 多选题：可以选择多个选项' 
                      : '📌 单选题：只能选择一个选项'}
                  </div>
                  {currentQuestion.options.map((option, index) => {
                    const isMultipleChoice = currentQuestion.type === 'multiple_choice' || currentQuestion.type === 'indefinite_choice'
                    const isSelected = isMultipleChoice 
                      ? selectedAnswers.includes(option)
                      : selectedAnswer === option
                    
                    return (
                      <button
                        key={index}
                        className={`option-button ${isSelected ? 'selected' : ''}`}
                        onClick={() => handleOptionClick(option)}
                      >
                        {isMultipleChoice && isSelected && '✓ '}
                        {option}
                      </button>
                    )
                  })}
                </div>
              )}

              <div className="question-actions">
                <button
                  className="submit-button"
                  onClick={submitAnswer}
                  disabled={
                    (currentQuestion.type === 'multiple_choice' || currentQuestion.type === 'indefinite_choice')
                      ? selectedAnswers.length === 0
                      : !selectedAnswer
                    || isLoading
                  }
                >
                  {isLoading ? '提交中...' : '提交答案'}
                </button>
              </div>
            </motion.div>
          )}

          {/* 答案结果区域 */}
          <AnimatePresence>
            {answerResult && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -20 }}
                className={`result-card ${answerResult.is_correct ? 'correct' : 'incorrect'}`}
              >
                <div className="result-header">
                  <h3>{answerResult.is_correct ? '✓ 回答正确' : '✗ 回答错误'}</h3>
                  <div className="result-stats">
                    <span>得分: {answerResult.score}</span>
                    <span>用时: {formatTime(answerResult.time_spent)}</span>
                  </div>
                </div>

                <div className="result-content">
                  <div className="answer-comparison">
                    <div>
                      <strong>你的答案:</strong> {answerResult.user_answer}
                    </div>
                    <div>
                      <strong>正确答案:</strong> {answerResult.correct_answer}
                    </div>
                  </div>

                  <div className="explanation">
                    <strong>解析:</strong>
                    <p>{answerResult.explanation}</p>
                  </div>

                  {/* 详细分析（答对时：做题思路和为什么正确；答错时：错误分析） */}
                  {answerResult.detailed_analysis && (
                    <div className="detailed-analysis">
                      <h4>
                        {answerResult.is_correct
                          ? '✅ 做题思路分析'
                          : '📝 详细错误分析'}
                      </h4>
                      {typeof answerResult.detailed_analysis === 'string' ? (
                        <div className="analysis-content">
                          <pre style={{ whiteSpace: 'pre-wrap', fontFamily: 'inherit' }}>
                            {answerResult.detailed_analysis}
                          </pre>
                        </div>
                      ) : (
                        <div className="analysis-content">
                          {answerResult.detailed_analysis.detailed_analysis && (
                            <div className="analysis-text">
                              <pre style={{ whiteSpace: 'pre-wrap', fontFamily: 'inherit' }}>
                                {answerResult.detailed_analysis.detailed_analysis}
                              </pre>
                            </div>
                          )}
                          {answerResult.detailed_analysis.thinking_approach && (
                            <div className="thinking-approach">
                              <strong>💭 做题思路：</strong>
                              <p>{answerResult.detailed_analysis.thinking_approach}</p>
                            </div>
                          )}
                          {answerResult.detailed_analysis.correct_answer_explanation && (
                            <div className="correct-explanation">
                              <strong>✅ 为什么正确：</strong>
                              <p>{answerResult.detailed_analysis.correct_answer_explanation}</p>
                            </div>
                          )}
                          {answerResult.detailed_analysis.error_analysis && (
                            <div className="error-explanation">
                              <strong>❌ 错误分析：</strong>
                              <p>{answerResult.detailed_analysis.error_analysis}</p>
                            </div>
                          )}
                        </div>
                      )}
                    </div>
                  )}

                  {/* 思维分析结果 */}
                  {thinkingAnalysis && (
                    <div className="thinking-analysis">
                      <h4>🧠 思维分析</h4>
                      <div className="analysis-score">
                        <strong>思维质量分数：</strong>
                        <span className={`score ${thinkingAnalysis.thinking_quality_score >= 80 ? 'high' : thinkingAnalysis.thinking_quality_score >= 60 ? 'medium' : 'low'}`}>
                          {thinkingAnalysis.thinking_quality_score} 分
                        </span>
                        {thinkingAnalysis.bert_enhanced && (
                          <span className="bert-badge">✨ Legal-BERT增强</span>
                        )}
                      </div>
                      
                      {thinkingAnalysis.strengths.length > 0 && (
                        <div className="analysis-strengths">
                          <strong>✅ 优势：</strong>
                          <ul>
                            {thinkingAnalysis.strengths.map((strength, idx) => (
                              <li key={idx}>{strength}</li>
                            ))}
                          </ul>
                        </div>
                      )}
                      
                      {thinkingAnalysis.weaknesses.length > 0 && (
                        <div className="analysis-weaknesses">
                          <strong>⚠️ 薄弱点：</strong>
                          <ul>
                            {thinkingAnalysis.weaknesses.map((weakness, idx) => (
                              <li key={idx}>{weakness}</li>
                            ))}
                          </ul>
                        </div>
                      )}
                      
                      {thinkingAnalysis?.reasoning_chain && (
                        <div className="reasoning-chain">
                          <strong>推理链条：</strong>
                          <div className="chain-item">
                            <span className="chain-label">大前提：</span>
                            {thinkingAnalysis.reasoning_chain.major_premise?.provisions?.length > 0
                              ? thinkingAnalysis.reasoning_chain.major_premise.provisions.join('、')
                              : '未识别到法律条文'}
                          </div>
                          <div className="chain-item">
                            <span className="chain-label">小前提：</span>
                            {thinkingAnalysis.reasoning_chain.minor_premise?.facts?.length > 0
                              ? `${thinkingAnalysis.reasoning_chain.minor_premise.facts.length} 个关键事实`
                              : '未提取到关键事实'}
                          </div>
                          <div className="chain-item">
                            <span className="chain-label">完整性：</span>
                            {thinkingAnalysis.reasoning_chain.reasoning_completeness ? (
                              <span className={`completeness ${thinkingAnalysis.reasoning_chain.reasoning_completeness.level || 'unknown'}`}>
                                {thinkingAnalysis.reasoning_chain.reasoning_completeness.level || '未知'} 
                                ({thinkingAnalysis.reasoning_chain.reasoning_completeness.score || 0}分)
                              </span>
                            ) : (
                              <span>未评估</span>
                            )}
                          </div>
                        </div>
                      )}
                      
                      {thinkingAnalysis.improvement_suggestions.length > 0 && (
                        <div className="improvement-suggestions">
                          <strong>💡 改进建议：</strong>
                          <ul>
                            {thinkingAnalysis.improvement_suggestions.map((suggestion, idx) => (
                              <li key={idx}>{suggestion}</li>
                            ))}
                          </ul>
                        </div>
                      )}
                    </div>
                  )}
                </div>

                <div className="result-actions">
                  <button 
                    className="debate-button"
                    onClick={async () => {
                      // 进入辩论模式
                      if (currentQuestion) {
                        try {
                          const session = await debateApi.startDebate(
                            userId,
                            currentQuestion.question_id,
                            currentQuestion.content,
                            '中立',
                            currentQuestion.options || []
                          )
                          setDebateSession(session)
                          setShowDebate(true)
                        } catch (error) {
                          console.error('启动辩论失败:', error)
                        }
                      }
                    }}
                  >
                    💬 进入辩论
                  </button>
                  <button className="continue-button" onClick={continueNext}>
                    下一题
                  </button>
                </div>
              </motion.div>
            )}
          </AnimatePresence>

          {!currentQuestion && !answerResult && (
            <div className="loading-state">
              <p>加载题目中...</p>
            </div>
          )}
        </div>
      )}

      {/* 辩论面板（模态显示） */}
      <AnimatePresence>
        {showDebate && currentQuestion && debateSession && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="debate-modal-overlay"
            onClick={() => setShowDebate(false)}
          >
            <motion.div
              initial={{ scale: 0.9, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.9, opacity: 0 }}
              className="debate-modal-content"
              onClick={(e) => e.stopPropagation()}
            >
              <div className="debate-modal-header">
                <h2>辩论训练</h2>
                <button
                  className="close-button"
                  onClick={() => setShowDebate(false)}
                >
                  ✕
                </button>
              </div>
              <div className="debate-modal-body">
                <DebatePanel
                  userId={userId}
                  questionId={currentQuestion.question_id}
                  questionContent={currentQuestion.content}
                  questionOptions={currentQuestion.options}
                  onNavigate={(tab) => {
                    if (tab === 'training') {
                      setShowDebate(false)
                    }
                  }}
                />
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  )
}

export default TrainingPanel

